<?php


namespace app\app\controller\user;


use app\model\MenuModel;
use app\model\RoleMenuModel;
use app\model\UserRoleModel;
use support\Request;

class Menu
{
    protected $user_id = 0;

    public function beforeAction(Request $request){
        $this->user_id = $request->user_id;

    }

    public function get(){
        $menuModel = new MenuModel();
        $roleMenuModel = new RoleMenuModel();
        $role_id_lst = UserRoleModel::where(['user_id'=>$this->user_id])->column("role_id");
        $role_menu_lst = $roleMenuModel->where([['role_id','in',$role_id_lst]])->select();
        $idArr = [];
        foreach ($role_menu_lst as $k=>$v){
            $idArr[] = $v['menu_id'];
        }
        $ids = implode(",", $idArr);
        $where[]=['hide','=',0];
        $where[]=['parent_id','=',0];
        $where[]=['menu_type','=',0];
        if(!in_array(1,$role_id_lst)){
            $where[]=['menu_id','in',$ids];
        }
        $menu_lst = $menuModel->field('menu_id as menuId, parent_id as parentId,title,path,target,icon,hide')->where($where)->order('sort_number asc')->select();
        foreach ($menu_lst as $k=>&$v){
            if(!in_array(1,$role_id_lst)){
                $v['children'] = $menuModel->field('menu_id as menuId, parent_id as parentId,title,path,target,icon,hide')->where([
                    ['parent_id','=',$v['menuId']],
                    ['menu_id','in',$ids]
                ])->order('sort_number asc')->select();
            }
            else{
                $v['children'] = $menuModel->field('menu_id as menuId, parent_id as parentId,title,path,target,icon,hide')->where([
                    ['parent_id','=',$v['menuId']]
                ])->order('sort_number asc')->select();
            }
        }
        return success($menu_lst);
    }
}